package org.wlgzs.shop.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.wlgzs.shop.bean.*;
import org.wlgzs.shop.dao.GoodsDataMapper;
import org.wlgzs.shop.dao.PersonProblemAllMapper;
import org.wlgzs.shop.dao.UserDateMapper;
import org.wlgzs.shop.service.IGoodsDateService;
import org.wlgzs.shop.service.IUserDateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wlgzs.shop.service.IUserPhoto;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

@Service(value = "userDateService")
public class UserDateServiceImpl implements IUserDateService {

    @Autowired
    UserDateMapper userDateMapper;

    @Autowired
    PersonProblemAllMapper problemAllMapper;

    @Autowired
    IUserPhoto iUserPhoto;

    @Autowired
    GoodsDataMapper goodsDataMapper;


    private static final Logger logger = LoggerFactory.getLogger(UserDateServiceImpl.class);

    /**
     *增加用户信息Service层实现
     * @param userDate
     * @return boolean
     */
    @Override
    public boolean registeredInsertService(UserDate userDate) {
        UserDate data=userAccountSelectUser(userDate.getUserName());
        if(data==null) {
            userDate.setPower(2);
            userDateMapper.insert(userDate);
            logger.info("注册成功！");
            return true;
        }
        else{
            return false;
        }
    }

    /**
     *根据id查询用户信息Service层实现
     * @param userId
     * @return UserDate
     */
    @Override
    public UserDate registeredSelectService(int userId) {
        UserDate userDate=userDateMapper.selectByPrimaryKey(userId);
        return userDate;
}

    /**
     *根据账号查询用户信息
     * @param account
     *
     * @return UserDate
     */
    @Override
    public UserDate userAccountSelectUser(String account){
        UserDateExample userDateExample=new UserDateExample();
        UserDateExample.Criteria criteria= userDateExample.createCriteria();
        criteria.andUserNameEqualTo(account);
        List<UserDate> data=userDateMapper.selectByExample(userDateExample);
        if(data!=null&&data.size()!=0) {
            return data.get(0);
        }
        else {
            return null;
        }
    }


//用户登陆
    @Override
    public boolean loginUser(UserDate userDate, HttpSession session) {
        if(userDate==null){
            return false;
        }
        else{
           UserDate really=userAccountSelectUser(userDate.getUserName());
           if(really==null){
               System.out.println("============falseNull=================");
               return false;
           }
           else if(really.getPassword().equals(userDate.getPassword())){
               session.setAttribute("user",really);
               userPhoto photo=iUserPhoto.selectDate(really.getUserId());
                if(photo!=null){
                    System.out.println("photo");
                   session.setAttribute("photo",photo.getPhotoname());
               }
               System.out.println("============true=================");
               return true;
           }
           else{
               System.out.println("============false=================");
               return false;
           }
        }
    }

    //修改密码操作
    @Override
    public Msg setUserPassword(UserDate date) {
        int num=userDateMapper.updateByPrimaryKeySelective(date);
        if(num!=0){
            return Msg.success();
        }
        return Msg.fail();
    }


//获取用户所有密保信息
    public List<PersonProblemAll> getAllProblem(int userId){
        PersonProblemAllExample problemAllExample=new PersonProblemAllExample();
        PersonProblemAllExample.Criteria criteria=problemAllExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        List<PersonProblemAll> personProblemAlls=problemAllMapper.selectByExample(problemAllExample);
        return personProblemAlls;
    }

//根据用户账号获取密码操作
    @Override
    public Msg getPass(String account, String answer, int problemId) {
        UserDate userDate=userAccountSelectUser(account);
        int userId=userDate.getUserId();
        List<PersonProblemAll> personProblemAlls= getAllProblem(userId);
        System.out.println(personProblemAlls.size()+"\n\n");
        for(PersonProblemAll date:personProblemAlls){
            System.out.println(date);
            if(date.getProblemId()==problemId&&date.getAnswer().equals(answer)){
                try {
                    SendEmail.sendEmail("小金库",userDate.getPost(),"身份验证成功！","用户为："+userDate.getUserName()+"的用户,您的密码为："+userDate.getPassword());
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return new Msg().add("error","邮件发送失败!");
                } catch (MessagingException e) {
                    e.printStackTrace();
                    return new Msg().add("error","邮件发送失败!");
                }
                return Msg.success();
            }
        }
        return new Msg().add("error","身份验证失败！");
    }

    //邮箱发送验证码
    @Override
    public Boolean sentEmail(HttpSession session,String post) {
        try {
            SendEmail.sendCode(post,session);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    //完善用户信息

    //获取所有用户
    @Override
    public List<UserDate> allUser(){
        return userDateMapper.selectByExample(null);
    }


    //上传文件
    @Override
    public Msg upLoad(MultipartFile file,HttpSession session, HttpServletRequest request) throws IOException {
        UserDate userDate=(UserDate) session.getAttribute("user");
        String end=file.getOriginalFilename().split("\\.")[1];
        String path = request.getSession().getServletContext().getRealPath("/src/main/webapp/WEB-INF/static/img/");
        userPhoto photo=upFile(file,path);
        userPhoto photo2=iUserPhoto.selectDate(userDate.getUserId());
        photo.setId(userDate.getUserId());
        session.setAttribute("photo",photo.getPhotoname());
        if(iUserPhoto.selectDate(userDate.getUserId())!=null){
            File file3=new File(path+iUserPhoto.selectDate(userDate.getUserId()).getPhotoname());
            file3.delete();
        }
        iUserPhoto.upDate(photo);
        return Msg.success();
    }

    @Override
    public Msg addOrder(List<String> date) {
        System.out.println(date.toString()+"===============");
        return null;
    }

    @Override
    public Msg setPoint(UserDate date) {
        UserDate userDate=registeredSelectService(date.getUserId());
        date.setIntegral(date.getIntegral()+userDate.getIntegral());
        userDateMapper.updateByPrimaryKeySelective(date);
        return Msg.success();
    }

    @Override
    public List selectSameName(String name) {
        UserDateExample userDateExample=new UserDateExample();
        UserDateExample.Criteria criteria=userDateExample.createCriteria();
        criteria.andUserNameEqualTo(name);
        return userDateMapper.selectByExample(userDateExample);
    }

    @Override
    public Msg fewFileUp(MultipartFile[] files,HttpSession session, HttpServletRequest request,String twoKind) throws IOException {
        GoodsData goodsData=new GoodsData();
        goodsData.setGoodsKind(twoKind);
        String photoName=allFileUp(files,session,request);
        goodsData.setPhotoUrl(photoName);
        goodsDataMapper.insert(goodsData);
        return Msg.success();
    }

    public userPhoto upFile(MultipartFile file,String  path) throws IOException{
        String end=file.getOriginalFilename().split("\\.")[1];
        userPhoto photo=new userPhoto();
        InputStream is = file.getInputStream();
        Calendar calendar=Calendar.getInstance();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("ddHHhhmm");
        String time=simpleDateFormat.format(calendar.getTime());
        String name=path+time+"."+end;
        photo.setPhotoname(time+"."+end);
        File file2=new File(path);
        if(!file2.exists()){
            file2.mkdirs();
        }
        FileOutputStream os = new FileOutputStream(new File(name));
        int len = 0;
        byte[] buffer = new byte[100];
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        os.close();
        is.close();
        return photo;
    }

    @Override
    public String allFileUp(MultipartFile[] files,HttpSession session, HttpServletRequest request) throws IOException{
        String allName="";
        String path = request.getSession().getServletContext().getRealPath("/WEB-INF/static/img/");
        for (MultipartFile file:files) {
            String end=file.getOriginalFilename().split("\\.")[1];
            Calendar calendar=Calendar.getInstance();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("ddHHhhmm");
            String time=simpleDateFormat.format(calendar.getTime());
            allName+=time+"."+end+",";
            String name=path+time+"."+end;
            File file2=new File(path);
            if(!file2.exists()){
                file2.mkdirs();
            }
            InputStream is = file.getInputStream();
            FileOutputStream os = new FileOutputStream(new File(name));
            int len = 0;
            byte[] buffer = new byte[100];
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.close();
            is.close();
        }
        return allName;
    }

    @Override
    public String oneFilep(MultipartFile file, HttpSession session, HttpServletRequest request)throws IOException {
        String path = request.getSession().getServletContext().getRealPath("/WEB-INF/static/img/");
        String name=time()+"."+file.getOriginalFilename().split("\\.")[1];
        System.out.println(name);
        File fileOne=new File(path);
        if(fileOne.exists()){
            fileOne.mkdirs();
        }
        InputStream is = file.getInputStream();
        FileOutputStream os = new FileOutputStream(new File(path+name));
        int len = 0;
        byte[] buffer = new byte[100];
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        os.close();
        is.close();
    return name;
    }


    String time(){
        Calendar calendar=Calendar.getInstance();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("ddHHhhmm");
        return simpleDateFormat.format(calendar.getTime());
    }

}


